package com.galeno.day07;

import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.List;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2319:46
 */
public class UserEvent {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 23000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        env.enableCheckpointing(10000);
        DataStreamSource<String> lines = env.socketTextStream("galeno", 9999);
        SingleOutputStreamOperator<Tuple2<String, String>> tpStream = lines.map(x -> {
            String[] split = x.split(",");
            return Tuple2.of(split[0], split[1]);
        }).returns(new TypeHint<Tuple2<String, String>>() {
        });
        tpStream.print();
        KeyedStream<Tuple2<String, String>, String> keyedStream = tpStream.keyBy(x -> x.f0);
        keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, String>, Tuple2<String, List<String>>>() {
            private ListState<String> listState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ListStateDescriptor<String> listStateDescriptor = new ListStateDescriptor<>("event-state", String.class);
                listState = getRuntimeContext().getListState(listStateDescriptor);
            }

            @Override
            public void processElement(Tuple2<String, String> value, Context ctx, Collector<Tuple2<String, List<String>>> out) throws Exception {
                String event = value.f1;
                listState.add(event);
                ArrayList<String> events = (ArrayList<String>) listState.get();
                out.collect(Tuple2.of(value.f0, events));
            }
        }).print();
        env.execute("enent-job");
    }
}
